//
//  SSFotoSelectorCollectionViewController.swift
//  FotoSelector
//
//  Created by stevenSu on 15/8/7.
//  Copyright © 2015年 stevenSu. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"

class SSFotoSelectorCollectionViewController: UICollectionViewController, FotoSelectorCellDelegate {
    
    init() {
        super.init(collectionViewLayout: UICollectionViewFlowLayout())
        
        let layout = collectionView?.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: 80, height: 80)
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 10
        layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView?.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
        self.collectionView!.registerClass(FotoSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if selectedIndex == images.count - 1 {
            return images.count == maxImages ? images.count : images.count + 1
        } else {
            return images.count
        }
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! FotoSelectorCell
        cell.delegate = self
        return cell
    }
    
    private func fotoSelectorCellSelButtonClicked(cell: FotoSelectorCell) {
        
        if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) {
            return
        }
        
        selectedIndex = collectionView!.indexPathForCell(cell)!.item
        let vc = UIImagePickerController()
        vc.view.backgroundColor = UIColor.whiteColor()
        vc.delegate = self
        presentViewController(vc, animated: true, completion: nil)
    }
    
    private func fotoSelectorCellCancelButtonClicked(cell: FotoSelectorCell) {
        print("cancel")
        
        cell.selButton.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
        cell.selButton.setImage(UIImage(named: "compose_pic_add_highlighted"), forState: UIControlState.Highlighted)
        let indexPath = collectionView!.indexPathForCell(cell)!
        images[indexPath.item] = nil
        cell.cancelButton.hidden = true
    }
    
    private let maxImages = 3
    
    private var selectedIndex: Int = -1
    
     var images = [UIImage?]()
    
}
extension SSFotoSelectorCollectionViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        let resizedImage = resizeBigImage(image)
        
        let indexPath = NSIndexPath(forItem: selectedIndex, inSection: 0)
//        print(indexPath)
//        print(images.count)
        let cell = collectionView?.cellForItemAtIndexPath(indexPath) as! FotoSelectorCell
        // 选中最后一个cell
        if indexPath.item == images.count {
            images.append(resizedImage)
            cell.selButton.setImage(resizedImage)
            // 没到最大图片时，插入item
            if images.count != maxImages {
                collectionView?.insertItemsAtIndexPaths([NSIndexPath(forItem: selectedIndex + 1, inSection: 0)])
            }
        } else { // 选中前面的cell
            images[indexPath.item] = resizedImage
            cell.selButton.setImage(resizedImage)
        }
        cell.cancelButton.hidden = false
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    private func resizeBigImage(image: UIImage) -> UIImage {
        if image.size.width < 300 {
            return image
        }
        let w: CGFloat = 300
        let h = image.size.height * w / image.size.width
        let size = CGSize(width: w, height: h)
        UIGraphicsBeginImageContext(size)
        image.drawInRect(CGRect(origin: CGPointZero, size: size))
        let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return resizedImage
    }
}



private protocol FotoSelectorCellDelegate: NSObjectProtocol {
    func fotoSelectorCellSelButtonClicked(cell: FotoSelectorCell)
    func fotoSelectorCellCancelButtonClicked(cell: FotoSelectorCell)
}

private class FotoSelectorCell: UICollectionViewCell {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        prepareButton()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    weak var delegate: FotoSelectorCellDelegate?
    
    @objc func selBtnSelected() {
        delegate?.fotoSelectorCellSelButtonClicked(self)
    }
    
    @objc func cancelBtnSelected() {
        delegate?.fotoSelectorCellCancelButtonClicked(self)
    }
    
    private func prepareButton() {
        contentView.addSubview(selButton)
        contentView.addSubview(cancelButton)
        
        let dict = ["selButton": selButton, "cancelButton": cancelButton]
        selButton.translatesAutoresizingMaskIntoConstraints = false
        cancelButton.translatesAutoresizingMaskIntoConstraints = false
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[selButton]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[selButton]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[cancelButton]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cancelButton]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        
        cancelButton.hidden = true
        selButton.imageView!.contentMode = UIViewContentMode.ScaleAspectFill
        
        selButton.addTarget(self, action: "selBtnSelected", forControlEvents: UIControlEvents.TouchUpInside)
        cancelButton.addTarget(self, action: "cancelBtnSelected", forControlEvents: UIControlEvents.TouchUpInside)
    }
    
    private lazy var selButton: UIButton = UIButton(imgName: "compose_pic_add")
    private lazy var cancelButton: UIButton = UIButton(imgName: "compose_photo_close")
    
}
